package user

import (
	"gitee.com/fzh-show/mcube/pb/resource"

	"golang.org/x/crypto/bcrypt"
)

func NewUser(in *CreateUserRequest) *User {
	// 先对password做hash再保存.
	in.MakePasswordHash()
	return &User{
		Spec: in,
		Meta: resource.NewMeta(),
	}
}

func (c *CreateUserRequest) MakePasswordHash() {
	bytes, err := bcrypt.GenerateFromPassword([]byte(c.Password), 10)
	if err != nil {
		panic(err)
	}
	c.Password = string(bytes)

}

func NewCreateUserRequest() *CreateUserRequest {
	return &CreateUserRequest{}
}

func (u *User) CheckPassword(password string) error {

	return bcrypt.CompareHashAndPassword([]byte(u.Spec.Password), []byte(password))
}
